"""
created  by  hzwlxy  at 2018/7/4 12:26
__author__: 西瓜哥
__QQ__ : 120235331
__Note__： 
"""
from flask import render_template, request

from flask_login_multi import current_user

__author__ = '西瓜哥'
from app.ext import db
from app.web import admin_app as app
from app.forms.admin import AdminProfileForm,AdminPasswordForm
from app.libs.layui_response import Success, Fail



@app.route('/admin/create', methods=['get', 'post'])
def admin_create():
    return 'admin.create'


@app.route('/admin/profile', methods=['get', 'post'])
def admin_profile():
    form = AdminProfileForm(request.form)
    if request.method == "POST":
        if form.validate():
            user = current_user
            with db.auto_commit():
                user.set_attrs(form.data)
            return Success(message="操作成功！")
        return Fail(message=form.first_error)
    else:
        return render_template('admin/admin/profile.html')



@app.route('/admin/avatar/edit', methods=['get', 'post'])
def admin_edit_avatar():
    return 'edit avatar'


@app.route('/admin/password/edit', methods=['get', 'post'])
def admin_edit_password():
    """
    修改密码
    :return:
    """
    form = AdminPasswordForm(request.form)
    if request.method == "POST":
        if form.validate():
            user = current_user
            if not user.check_password(form.oldpassword.data):
                return Fail(message="原始密码错误！")
            if form.oldpassword.data == form.password.data:
                return Fail(message="新旧密码必须不一样！")
            with db.auto_commit():
                user.set_password(form.password.data)
            return Success(message="操作成功！")

        return Fail(message=form.first_error)
    else:
        return render_template('admin/admin/password.html')
